package com.lxh.libmanager.web.controller;


import com.github.pagehelper.PageInfo;
import com.lxh.libmanager.entity.Book;
import com.lxh.libmanager.services.BookServices;
import com.lxh.libmanager.util.StringUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookServices bookServices;


    @RequestMapping("/delBook")
    @ResponseBody
    public String delBook(Integer id,Model model){
        if(bookServices.delBook(id)){
            return "1";
        }else {
            return "0";
        }

    }


    @RequestMapping("/getBookById")
    public String getBookById(Integer id,Model model){
        model.addAttribute("b",bookServices.getBookById(id));
        return "updateBook";

    }


    @RequestMapping("/updateBook")
    public String updateBook(Book book,Model model){

        System.out.println("++++++++++++++++++++++++++++++++++++++++++++");
        System.out.println(book);
        System.out.println("++++++++++++++++++++++++++++++++++++++++++++");

        if(bookServices.updateBook(book)){
            model.addAttribute("msg","修改成功");
        }else {
            model.addAttribute("msg","修改失败");
        }
        return "message";
    }



    @RequestMapping("/addBook")
    public String addBook(Book book,Model model){
        if(bookServices.addBook(book)){
            model.addAttribute("msg","新增成功");
        }else {
            model.addAttribute("msg","新增失败");
        }
        return "message";
    }

    @RequestMapping("/getBookByPage")
    public String getBookByPage(@RequestParam Map<String,String> books, HttpSession session, Model model){

        //自定义分页大小
        if(session.getAttribute("pagesize")==null){
            session.setAttribute("pagesize", "5");
        }

        System.out.println(session.getAttribute("pagesize"));
        if(books.get("pageSize")==null){

            books.put("pageSize", String.valueOf(session.getAttribute("pagesize")));
        }else{
            session.setAttribute("pagesize", StringUtil.stringToInt(books.get("pageSize")));

        }

        PageInfo<Book> info = bookServices.getBookByPage(books);

        model.addAttribute("info",info);
        return "index";
    }


}
